<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>23canvas帧动画</title>
</head>
<style>
    canvas {
        border: 1px solid #ccc;
    }
</style>
<body>
<canvas width="600" height="400"></canvas>
<script>
    var myCanvas = document.querySelector('canvas');
    var ctx = myCanvas.getContext('2d');
    var image = new Image();
    image.onload = function () {
        /*图片加载完成*/
        /*动态的去获取当前图片的尺寸*/
        var imageWidth = image.width;
        var imageHeight = image.height;
        /*计算出一个小人物的大小*/
        var personWidth = imageWidth / 12;
        var personHeight = imageHeight / 2;
        /*为截取图片*/
        /*帧动画 在固定的时间间隔更换显示的图片 根据图片的索引*/
        var index = 0;
        var count = 0;
        /*绘制在画布的中心*/
        var x0 = (ctx.canvas.width - personWidth) / 2;
        var y0 = (ctx.canvas.height - personHeight) / 2;
        /* 9参数 img对象
       * 图片上定位的坐标 x y
       * 在图片上截取多大的区域 w h
       * 绘制在画布上的坐标
       * 图片的大小（不是裁剪 是缩放）
       * */
        ctx.drawImage(image, 0, 0, personWidth, personHeight, x0, y0, personWidth, personHeight);
        setInterval(function () {
            ctx.clearRect(x0, y0, personWidth, personHeight);
            ctx.drawImage(image, personWidth * index, personHeight * count, personWidth, personHeight, x0, y0, personWidth, personHeight);
            index++;
            if (index > 11 && count === 0) {
                index = 0;
                count++;
            } else if (index > 11 && count !== 0) {
                count = 0;
                index = 0;
            }
        }, 100)
    };
    image.src = 'image/grf.jpg'
</script>
</body>
</html>
